package top.shiyiri.set;

import org.junit.Test;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author Aunean
 * @date 2022/1/5
 */
public class TreeSetTest {

    /*
    1.向TreeSet中添加的数据，要求是相同类的对象
    2.两种排序方式：自然排序和定制排序
    3.自然排序中，比较两个对象是否相同的标准为：compareTo()返回0，不再是equals()。
     */
    @Test
    public void test1() {
        TreeSet<Object> set = new TreeSet<>();

        set.add(new User("Tom", 12));
        set.add(new User("Jerry", 19));
        set.add(new User("Anna", 11));
        set.add(new User("Marry", 16));
        set.add(new User("Tomas", 11));
        set.add(new User("Tomas", 14));

        for (Object obj: set) {
            System.out.println(obj);
        }
    }

    @Test
    public void test2() {
        Comparator<User> comparator = new Comparator<User>() {
            //按照年龄从小到大排列
            @Override
            public int compare(User o1, User o2) {
                return o1.getAge() - o2.getAge();
            }
        };
        TreeSet<User> set = new TreeSet<User>(comparator);

        set.add(new User("Tom", 12));
        set.add(new User("Jerry", 19));
        set.add(new User("Anna", 11));
        set.add(new User("Marry", 16));
        set.add(new User("Tomas", 11));
        set.add(new User("Tomas", 14));

        for (User user: set) {
            System.out.println(user);
        }
    }
}
